<template>
  <div class="mater-child-transfer-value">
    <je-table
      ref="xTable"
      border
      stripe
      auto-resize
      sync-resize
      show-overflow="ellipsis"
      keep-source
      draggable
      show-header-overflow
      resizable
      header-align="center"
      height="100%"
      :scroll-y="{ mode: 'wheel' }"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        showStatus: false,
      }"
      :row-config="{ isCurrent: true, isHover: true }"
      :store="tableData"
      size="mini"
      align="center"
    >
      <!-- :edit-rules="validRules" -->
      <je-table-column width="40">
        <template #header>
          <i class="icon fal fa-plus" @click="addRow"></i>
        </template>
        <template #default="{ row }">
          <i class="icon fal fa-times" @click="deleteRow(row)"></i>
        </template>
      </je-table-column>
      <je-table-column title="主功能字段名称" field="masterFuncName" :edit-render="{}">
        <template #edit="{ row }">
          <je-grid-select
            v-model:value="row.masterFuncName"
            name="masterFuncName"
            config-info="JE_CORE_RESOURCEFIELD,masterFuncName~masterFuncCode,RESOURCEFIELD_NAME~RESOURCEFIELD_CODE,S"
            :querys="querysFieldCodes(masterFuncId)"
            :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
          />
        </template>
      </je-table-column>
      <je-table-column title="主功能字段编码" width="25%" field="masterFuncCode"> </je-table-column>
      <je-table-column
        title="（子功能集合）字段名称"
        width="25%"
        field="subFuncName"
        :edit-render="{}"
      >
        <template #edit="{ row }">
          <je-grid-select
            v-model:value="row.subFuncName"
            name="subFuncName"
            config-info="JE_CORE_RESOURCEFIELD,subFuncName~subFuncCode,RESOURCEFIELD_NAME~RESOURCEFIELD_CODE,S"
            :querys="querysFieldCodes(subFuncId)"
            :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
          />
        </template>
      </je-table-column>
      <je-table-column title="（子功能集合）字段编码" width="25%" field="subFuncCode">
      </je-table-column>
    </je-table>
  </div>
</template>

<script>
  import { toRefs, reactive, defineComponent, onMounted, ref } from 'vue';
  import { Data, Grid, InputSelect, Modal } from '@jecloud/ui';

  import { GetPluginItemConfig as GetFormFieldConfigData } from '@/api/index';
  export default defineComponent({
    name: 'ChildFuncFieldSelectFunc',
    components: {
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeGridSelect: InputSelect.Grid,
    },
    props: {
      records: Object,
      transferValueCode: String,
    },
    emits: [],
    setup(props, { emit, expose }) {
      const state = reactive({
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        xTable: ref(),
        // 主功能id
        masterFuncId: props.records.RESOURCEFIELD_FUNCINFO_ID,
        subFuncId: props.records.id,
        formatData: '',
        validRules: {
          masterFuncName: [{ required: true, message: '该输入项为必填项' }],
          subFuncName: [{ required: true, message: '该输入项为必填项' }],
        },
      });

      const methods = {
        // 增加行数据
        addRow() {
          const record = {
            masterFuncName: '',
            masterFuncCode: '',
            subFuncName: '',
            subFuncCode: '',
          };
          state.tableData.insert(record, -1);
        },
        // 主功能字段名称
        querysFieldCodes(id) {
          return [
            {
              code: 'RESOURCEFIELD_FUNCINFO_ID',
              type: '=',
              value: id,
            },
            {
              code: 'RESOURCEFIELD_XTYPE',
              value: ['child', 'fieldset', 'displayfield', 'childfuncfield'],
              type: 'notIn',
              cn: 'and',
            },
          ];
        },
        formmatData(modal) {
          if (!state.tableData.data.length) {
            modal.close();
            return '';
          }
          const isHasEmpty = state.tableData.data.find(
            (item) => !item.masterFuncCode || !item.subFuncCode,
          );
          if (isHasEmpty) {
            Modal.alert('每一行单元格都是必填项！', 'error');
            return '';
          }
          const masterCodeArr = [];
          const subCodeArr = [];
          state.tableData.data.map((item) => {
            masterCodeArr.push(item.masterFuncCode);
            subCodeArr.push(item.subFuncCode);
            state.xTable.store.commitRecord(item);
          });
          modal.close();
          return `${masterCodeArr.join('~')},${subCodeArr.join('~')}`;
          // state.xTable.validate(state.tableData.data, (errMap) => {
          //   if (errMap) {
          //     console.log('校验不通过');
          //     return false;
          //   }

          // });
        },
        deleteRow(record) {
          state.tableData.remove(record);
        },
        getData(id, codeArr) {
          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            j_query: JSON.stringify({
              custom: [
                {
                  code: 'RESOURCEFIELD_FUNCINFO_ID',
                  value: id,
                  type: '=',
                  cn: 'and',
                },
                {
                  type: 'and',
                  value: [{ code: 'RESOURCEFIELD_CODE', value: codeArr, type: 'in' }],
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
            funcId: id,
          };
          return GetFormFieldConfigData(params)
            .then((res) => {
              return res.rows || [];
            })
            .catch((err) => {
              console.log(err);
            });
        },
      };
      onMounted(() => {
        const propsValue = props.transferValueCode || '';
        if (propsValue) {
          const formatValue = propsValue?.split(',');
          const masterCode = formatValue[0].split('~');
          const subCode = formatValue[1].split('~');
          Promise.all([
            methods.getData(state.masterFuncId, masterCode),
            methods.getData(state.subFuncId, subCode),
          ])
            .then((res) => {
              const data = [];
              state.tableData.data = [];
              masterCode.map((item, index) => {
                const record = {
                  masterFuncName: res[0][index].RESOURCEFIELD_NAME,
                  masterFuncCode: item,
                  subFuncName: res[1][index].RESOURCEFIELD_NAME,
                  subFuncCode: subCode[index],
                };
                data.push(record);
              });
              state.tableData.loadData(data);
            })
            .catch((err) => {});
        }
      });

      expose({ formmatData: methods.formmatData });
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style lang="less" scoped>
  .mater-child-transfer-value {
    height: 100%;
    .icon {
      font-size: 16px;
      cursor: pointer;
      text-align: center;
    }
  }
</style>
